package com.huan.xss.core;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * jackson xss 清理
 * @author huan.fu
 * @date 2022/10/24 - 20:48
 */
@Slf4j
@RequiredArgsConstructor
public class JacksonXssClean extends JsonDeserializer<String> {
    private final XssCleaner xssCleaner;

    @Override
    public String deserialize(JsonParser p, DeserializationContext deserializationContext) throws IOException {
        JsonToken jsonToken = p.getCurrentToken();
        if (JsonToken.VALUE_STRING != jsonToken) {
            throw MismatchedInputException.from(p, String.class,
                    "can't deserialize value of type java.lang.String from " + jsonToken);
        }
        // 解析字符串
        String text = p.getValueAsString();
        if (text == null) {
            return null;
        }
        String value = xssCleaner.clean(XssUtil.trim(text, false));
        log.info("Json属性值: {} 经过xss清除后的值为: {}.", text, value);
        return value;
    }
}
